'use strict';

const LOWEST_NODE_VERSION = '13.0.0'
const semver = require('semver')
const colors = require('colors')
const log = require('@fobiz-cli/log')

class Command {
    constructor(argv) {
        console.log()
        if (!argv) {
            throw new Error('参数不能为空！')
        }
        if (!Array.isArray(argv)) {
            throw new Error('参数必须为数组！')
        }
        if (argv.length < 1) {
            throw new Error('参数列表不能为空！')
        }
        this._argv = argv
        let runner = new Promise(resolve => {
            let chain = Promise.resolve()
            chain = chain.then(() => this.checkNodeVersion())
            chain = chain.then(() => this.initArgs())
            chain = chain.then(() => this.init())
            chain = chain.then(async () => await this.exec())
            chain.catch(err => {
                log.error(err.message)
            })
        })
    }

    checkNodeVersion() {
        // 获取当前版本号
        const currentVersion = process.version
        // 比对最低版本号
        if (!semver.gte(currentVersion, LOWEST_NODE_VERSION)) {
            throw new Error(colors.red(`fobiz-cli 需要安装 v${LOWEST_NODE_VERSION} 以上版本的 Node.js`))
        }
    }

    initArgs() {
        this.cmdObj = this._argv[this._argv.length - 1]
        this.opts = this._argv[this._argv.length - 2]
        this._argv = this._argv.slice(0, this._argv.length - 2)
    }

    init() {
        throw new Error('init方法必须实现')
    }

    exec() {
        throw new Error('exec方法必须实现')
    }
}

module.exports = Command;
